package com.rv.nats.resolver.reply;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rv.nats.enums.ClientType;
import io.nats.client.Message;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author SunDeZhi
 * @time 2023/8/1
 * @description :
 */
public class DefaultReplyResolver implements ReplyResolver {
    @Override
    public boolean match(ClientType clientType) {
        return true;
    }

    private ObjectMapper mapper = new ObjectMapper();


    public DefaultReplyResolver() {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    @Override
    public Object convertResult(Message message, Class<?> returnType) throws IOException {
        byte[] data = message.getData();
        if (data == null) {
            return null;
        }
        return convertResult(message , (Type) returnType);
    }

    // 新增支持泛型的方法
    @Override
    public Object convertResult(Message message, Type returnType) throws IOException {
        byte[] data = message.getData();
        if (data == null) {
            return null;
        }
        JavaType javaType = mapper.getTypeFactory().constructType(returnType);
        return mapper.readValue(data, javaType);
    }

}
